package com.yixun.driver.service.http;
import org.apache.http.NameValuePair;
import org.apache.http.client.config.RequestConfig;
import org.apache.http.client.entity.UrlEncodedFormEntity;
import org.apache.http.client.methods.CloseableHttpResponse;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.client.utils.URIBuilder;
import org.apache.http.entity.StringEntity;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.message.BasicNameValuePair;
import org.apache.http.util.EntityUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.util.StringUtils;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import static com.sun.org.apache.xml.internal.serialize.OutputFormat.Defaults.Encoding;

@Service
public class HttpAPIService implements IHttpAPIService{

    @Autowired
    private CloseableHttpClient httpClient;

    @Autowired
    private RequestConfig config;

    //不带参数的get请求，如果状态码为200，则返回body，如果不为200，则返回null
    public String doGet(String url) throws Exception
    {
        // 声明 http get 请求
        HttpGet httpGet = new HttpGet(url);

        //Request不会继承客户端级别的请求配置，所以在自定义Request的时候，
        // 需要将客户端的默认设置过去
        // 装载配置信息
        httpGet.setConfig(config);

        // 发起请求
        CloseableHttpResponse response = this.httpClient.execute(httpGet);
        if(response.getStatusLine().getStatusCode()==200)
        {
            // 返回响应体的内容
            return EntityUtils.toString(response.getEntity(), "UTF-8");
        }

        return  null;
    }


    //带参数的get请求，如果状态码为200，则返回body，如果不为200，则返回null
    public String doGet(String url, Map<String, Object> map) throws Exception {
        URIBuilder uriBuilder = new URIBuilder(url);

        //Map中采用Entry内部类来表示一个映射项，
        // 映射项包含Key和Value (我们总说键值对键值对, 每一个键值对也就是一个Entry)
        //Map.Entry里面包含getKey()和getValue()方法
        // 遍历map,拼接请求参数

        //第一种：普遍使用，二次取值
        //System.out.println("通过Map.keySet遍历key和value：");
        //for (String key : map.keySet()) {
            //System.out.println("key= "+ key + " and value= " + map.get(key));
        //}

        ////第三种：推荐，尤其是容量大时
        //Set<String> set = map.keySet();
        if(map != null){
            for (Map.Entry<String, Object> entry : map.entrySet()) {
                uriBuilder.setParameter(entry.getKey(), entry.getValue().toString());
            }
        }

        // 调用不带参数的get请求
        return this.doGet(uriBuilder.build().toString());
    }

    //带参数的post请求
    public String doPost(String url, Map<String, Object> map) throws Exception{
        // 声明httpPost请求
        HttpPost httpPost = new HttpPost(url);
        // 加入配置信息
        httpPost.setConfig(config);

        // 判断map是否为空，不为空则进行遍历，封装from表单对象    看到这个
        if (map != null) {
            List<NameValuePair> list = new ArrayList<NameValuePair>();
            for (Map.Entry<String, Object> entry : map.entrySet()) {
                list.add(new BasicNameValuePair(entry.getKey(), entry.getValue().toString()));
            }
            // 构造from表单对象  list存放的参数是实现了NameValuePair类的引用，
            UrlEncodedFormEntity urlEncodedFormEntity = new UrlEncodedFormEntity(list, "UTF-8");

            // 把表单放到post里
            httpPost.setEntity(urlEncodedFormEntity);
        }

        // 发起请求
        CloseableHttpResponse response = this.httpClient.execute(httpPost);
        return EntityUtils.toString(response.getEntity(), "UTF-8");
    }
    //带请求体的post请求
    public String doPost(String url, String body) throws Exception{
        // 声明httpPost请求
        HttpPost httpPost = new HttpPost(url);
        // 加入配置信息
        httpPost.setConfig(config);
        httpPost.setHeader("Content-Type","application/json");

        if(!StringUtils.isEmpty(body)){//为false部位空
            //添加body
            httpPost.setEntity(new StringEntity(body, Encoding));
//            ByteArrayEntity entity = null;
//            try {
//                entity = new ByteArrayEntity(body.getBytes("UTF-8"));
//                entity.setContentType("application/json");
//            } catch (UnsupportedEncodingException e) {
//                throw new RuntimeException("向服务器承保接口发起http请求,封装请求body时出现异常", e);
//            }
//            httpPost.setEntity(entity);
        }

        // 发起请求
        CloseableHttpResponse response = this.httpClient.execute(httpPost);
        return EntityUtils.toString(response.getEntity(), "UTF-8");
    }

    //不带参数post请求
    public String doPost(String url) throws Exception{
        return this.doPost(url, new HashMap<>());
    }

}
